@{
    Layout = null;
    var previewId = ViewContext.RouteData.Values["id"];
}

<style asp-name="bootstrap"></style>
<script asp-name="bootstrap" at="Foot"></script>
<script asp-src="~/OrchardCore.Templates/js.cookie.js" depends-on="jquery" at="Foot"></script>

<resources type="Header" />

<iframe id="iframe" style="display:none; position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden;z-index:999990;">
    Your browser doesn't support iframes
</iframe>

<iframe id="iframe2" style="display:none; position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden;z-index:999990;">
    Your browser doesn't support iframes
</iframe>

<div id="notConnectedWarning" class="alert alert-info alert-dismissible fade show collapse" role="alert" style="position:fixed; height:60px; top:10px;right:40px; display:none; z-index:999999;">
    <button type="button" id="close-connect-warning" class="close" aria-label="Close" style="position: relative; padding: 0 0 0 1rem; margin-top: -0.2rem;">
        <span aria-hidden="true">&times;</span>
    </button>
    <span>@T["Preview Disconnected"] </span>
</div>

<div id="serverErrorWarning" class="alert alert-warning alert-dismissible fade show" role="alert" style="position:fixed; top:10px;right:40px; display:none; z-index:999999;">
    <button type="button" id="close-server-warning" class="close" aria-label="Close" style="position: relative; padding: 0 0 0 1rem; margin-top: -0.2rem;">
        <span aria-hidden="true">&times;</span>
    </button>
    <p>@T["Preview Error"] </p>
    <ul></ul>
</div>

<div id="renderPreviewUrl" style="display:none" data-value="@Url.Action("Render", "Preview", new { area = "OrchardCore.ContentPreview" })"></div>

<resources type="Footer" />

<script type="text/javascript">
    var renderPreviewUrl = $(document.getElementById('renderPreviewUrl')).data('value');
    var iframe = document.getElementById('iframe');
    var iframe2 = document.getElementById('iframe2');
    var previewEventTimer = null;
    var previewRenderTimer = null;

    $(function () {
        $(window).on('storage', function (ev) {
            if (ev.key.indexOf('contentpreview:not-connected:') !== -1) {
                $(notConnectedWarning).show();
            }
            else if (ev.key.indexOf('contentpreview:') !== -1) {
                if (ev.originalEvent.newValue != null) {
                    // Smooth event cascading
                    clearTimeout(previewEventTimer);
                    previewEventTimer = setTimeout(function () { renderPreview(ev.originalEvent.newValue); }, 150);
                    $(notConnectedWarning).hide();
                }
            }
        });

        // override default behaviour of Bootstrap's. We only hide, not remove the alert.
        $('#close-connect-warning').on('click', function(){
            $('#notConnectedWarning').hide();
        });

        $('#close-server-warning').on('click', function () {
            $('#serverErrorWarning').hide();
        });

        var preview = localStorage.getItem('contentpreview:@previewId');

        if (preview == null) {
            // notify the editor to render the preview
            localStorage.setItem('contentpreview:ready:@previewId', '');
            localStorage.removeItem('contentpreview:ready:@previewId');
        }
        else {
            renderPreview(preview);
        }
    });

    iframe.onload = function () {
        if (previewRendering) {
            this.style.display = 'block';
            $(this.contentWindow).scrollTop(scrollTop);

            if (iframe2 && iframe2.contentWindow) {
                iframe2.style.display = 'none';
                iframe2.contentWindow.document.open();
                iframe2.contentWindow.document.write(previewRenderData);
                iframe2.contentWindow.document.close();
            }
            previewRendering = false;
        }
    }

    var previewRendering;
    var previewRenderData;
    var scrollTop = 0;

    function renderPreview(value) {

        if (previewRendering) {
            // Defer the last rendering
            clearTimeout(previewRenderTimer);
            previewRenderTimer = setTimeout(function () { renderPreview(value); }, 100);
            return;
        }

        previewRendering = true;
        clearTimeout(previewRenderTimer);

        try {
            var formData = JSON.parse(value);
            if (!formData) {
                previewRendering = false;
                return;
            }

            $.post(renderPreviewUrl, formData)
                .done(function (data) {
                    if (iframe && iframe.contentWindow && iframe2 && iframe2.contentWindow) {

                        // A full writing of the frame document causes the iframe to be re-loaded.
                        // So, better to update the scroll position on the related 'onload' event.
                        // Then, we use 2 frames to cancel the flicker that this deferring causes.

                        scrollTop = $(iframe.contentWindow).scrollTop();
                        iframe2.style.display = 'block';
                        $(iframe2.contentWindow).scrollTop(scrollTop);

                        iframe.style.display = 'none';
                        iframe.contentWindow.document.open();
                        iframe.contentWindow.document.write(data);
                        iframe.contentWindow.document.close();
                        previewRenderData = data;
                    }
                    $(serverErrorWarning).hide();
                })
                .fail(function (data) {
                    if (data.responseJSON && data.responseJSON.errors) {
                        var ul = $('#serverErrorWarning ul').empty();
                        data.responseJSON.errors.forEach(function (error) {
                            console.error(error);
                            $('<li />').text(error).appendTo(ul);
                        });
                        $(serverErrorWarning).show();
                    }
                    previewRendering = false;
                });
        }
        catch (e) {
            previewRendering = false;
            console.log('Error while previewing: ' + e);
        }
    }
</script>
